package renthouse.util;/*
 * @创建者：黄苟苟
 * @创建时间：2021/5/18   16:54
 * @Description描述 jdbc连接
 **/


import java.sql.*;

/*数据库连接*/
public class ConnDb {

    public static final String url = "jdbc:mysql://localhost:3306/renthouse?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false";
    public static final String userName = "root";
    public static final String passWord = "123456";

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");   //加载驱动程序
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取一个数据库连接
     *
     * @return
     */

    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, userName, passWord);
            System.out.println("数据库连接成功");
        } catch (SQLException e) {
            System.out.println("获取数据库连接失败");
        }
        return connection;
    }

    /**
     * 创建一个可执行sql 语句的 stateMent 对象
     *
     * @param connection
     * @return
     */
    public static Statement getStatement(Connection connection) {
        Statement statement = null;
        try {
            statement = connection.createStatement();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return statement;
    }

    /**
     * 统一关闭方法
     *
     * @param connection
     * @param statement
     */
    public static void close(Connection connection, Statement statement, ResultSet resultSet) {

        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

